package com.cn.lp.openapi.param;

import com.cn.lp.common.utils.BlankAide;
import com.cn.lp.openapi.reflect.GClass;
import com.cn.lp.openapi.reflect.GPropertyAccessor;
import com.cn.lp.openapi.reflect.GSsistAide;
import feign.Util;
import feign.template.UriUtils;

import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public abstract class RequestParamBean implements RequestParam {

    private Map<String, Object> dataMap = new HashMap<>();

    @Override
    public void initMap(boolean encodeValue, Charset charset) {
        try {
            GClass gClass = GSsistAide.getGClass(getClass());
            Map<String, GPropertyAccessor> accessorMap = gClass.getAccessorMap();
            if(BlankAide.isNotBlank(accessorMap)) {
                for (Entry<String, GPropertyAccessor> entry : accessorMap.entrySet()) {
                    GPropertyAccessor accessor = entry.getValue();
                    Object propertyValue = accessor.getPropertyValue(this);
                    if(BlankAide.isNotBlank(propertyValue)) {
                        String name = accessor.getName();
                        if(BlankAide.isNotBlank(accessor.getAlias())) {
                            name = accessor.getAlias();
                        }
                        dataMap.put(name, encodeValue ? UriUtils.encode(propertyValue.toString(), charset)
                            : propertyValue.toString());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int size() {
        return dataMap.size();
    }

    @Override
    public boolean isEmpty() {
        return dataMap.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return dataMap.containsKey(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return dataMap.containsValue(value);
    }

    @Override
    public Object get(Object key) {
        return dataMap.get(key);
    }

    @Override
    public Object put(String key, Object value) {
        return dataMap.put(key, value);
    }

    @Override
    public Object remove(Object key) {
        return dataMap.remove(key);
    }

    @Override
    public void putAll(Map<? extends String, ?> m) {
        dataMap.putAll(m);
    }

    @Override
    public void clear() {
        dataMap.clear();
    }

    @Override
    public Set<String> keySet() {
        return dataMap.keySet();
    }

    @Override
    public Collection<Object> values() {
        return dataMap.values();
    }

    @Override
    public Set<Entry<String, Object>> entrySet() {
        return dataMap.entrySet();
    }

}
